/**
 * Created by Administrator on 2017/1/16.
 */
var config = require('./config');
var MJPlayer = require('../MJ/player').MJPlayer;
var MJ = require('../MJ/MJ');
var Const = require('./const');

exports.HLMJPlayer = MJPlayer.extend({

    _selectPiao: -1,     // 定漂
    _maScore: 0,         // 中码数
    _huCardType: {},     // 胡牌的亮牌
    _gangScore: 0,       // 杠分
    _kanNum: 0,          // 坎数
    _huCount: 0,         // 胡牌次数
    _dealerCount: 0,     // 连庄次数
    _dianCount: 0,       // 点炮次数
    _lastGangRate: 1,    // 最后一次杠的倍率
    _isZM: false,       // 是否自摸
    _showStatus: false, // 是否已经显示亮倒的牌型
    _LDResult: {},        // 当前是亮倒的牌

    init: function(uid, msg) {
        this._super(uid, msg);

        this._selectPiao = -1;
        this._maScore = 0;
        this._huCardType = {};
        this._kanNum = 0;
        this._gangScore = 0;
        this._huCount = 0;
        this._dealerCount = 0;
        this._dianCount = 0;
        this._lastGangRate = 1;
        this._isZM = false;
        this._showStatus = false;
        this._LDResult = {};
    },

    addDealerCount: function () {
        this._dealerCount += 1;
    },

    addHuCount: function () {
        this._huCount += 1;
    },

    addDianHuCount : function () {
        this._dianCount += 1;
    },

    addGangScore: function (score) {
        this._gangScore += score;
    },

    setSelectPiao: function (piao) {
        this._selectPiao = piao;
    },

    getSelectPiao: function () {
        return this._selectPiao;
    },

    setIsZm : function (zm) {
        this._isZM = zm;
    },

    isZm : function () {
        return this._isZM;
    },

    isSelectPiao: function () {
        return this._selectPiao != -1;
    },

    setMaScore : function (maPoint) {
        this._maScore = maPoint;
    },

    getMaScore : function () {
        return this._maScore;
    },

    setGangRate : function (gangRate) {
        this._lastGangRate = gangRate;
    },

    getHandKan : function () {



    },

    getShowStatus: function () {
        return this._showStatus;
    },

    /**
     * 判断当前牌是否和听牌相同
     * @param card
     * @returns {boolean}
     */
    judgeTingCard: function (card) {
        var tings = this.getTingCards();

        for (var index = 0; index < tings.length; ++index) {
            if (tings[index].card == card) {
                return true;
            }
        }

        return false;
    },

    /**
     * 获取对应听牌获取的亮牌数列
     * @param tingCard
     * @returns {Array}
     */
    getCheckArray: function (tingCard) {

        var handCards = clone(this._handCards.getCards());
        var result = [];

        // 特殊处理
        if (MJ.getColor(tingCard) == MJ.Color.ZI) {
            var newResult = {};
            newResult[tingCard] = handCards[tingCard];
            result.push (newResult);
            // 获取到所有的字牌
            return result;
        }

        // 普通情况， 需要将听牌填入, 然后相关听牌数量少一
        ExObject.addNumber(handCards, tingCard, 1);

        // 然后将对应的牌拆出来，然后放入队列中
        var newColor = MJ.getColor (tingCard);
        var colorMin = MJ.getValue (newColor, 1);
        var colorMax = MJ.getValue (newColor, 9);
        var resultCards = MJ.getColorCards(handCards, newColor);

        var newArray = MJ.splitColorCards (colorMin, colorMax, resultCards); // [[xx, xx]] 拆出来的类似于这种形式

        if (newArray.length < 1) {
            return result;
        }

        // 获取拆分列表
        newArray.forEach (function (arrays){

            var tempArray = {};
            arrays.forEach (function (array) {
                // 如果在对应的队列中能够获取到， 则对应的显示出来
                var isExist = false;

                for (var arrIndex = 0; arrIndex < array.length; ++arrIndex) {
                    if (this.judgeTingCard (array[arrIndex])) {
                        isExist = true;
                        break;
                    }
                }

                if (!isExist) {
                    return;
                }

                // 将对应的值导入
                for (var index = 0; index < array.length; ++index) {
                    var card = array[index];
                    if (tempArray[card]) {
                        tempArray[card] += 1
                    }else {
                        tempArray[card] = 1;
                    }
                }
            }, this);

            // 将听牌的牌值删除
            if (tempArray[tingCard] == 1) {
                tempArray[tingCard] = undefined;
            }else if (tempArray[tingCard] > 1){
                tempArray[tingCard] -= 1;
            }

            result.push (tempArray);
        }, this);

        return result;
    },

    /**
     * 获取当前玩家的亮倒牌型
     * @returns {{}}
     */
    checkShowCards : function () {

        // 显示当前亮牌为真
        this._showStatus = true;

        var resultTingArray = {};
        var tempArray = [];

        this.getTingCards().forEach(function(ting) {
            var curTingArray = this.getCheckArray(ting.card);
            curTingArray.forEach (function (array) {
                tempArray.push(array);
            }, this);
        }, this);

        // 将对应的听牌中重复的值进行删除
        tempArray.forEach (function (array) {
            ExObject.each (array, function (key, value) {
                if (value) {
                    // 只有如果结果队列中听牌的值小于 当前听牌的值, 那么则需要进行替换
                    if ((resultTingArray[key] && resultTingArray[key] < value)
                        || !resultTingArray[key]) {
                        resultTingArray[key] = value;
                    }
                }
            });
        }, this);

        this._LDResult = resultTingArray;

        return resultTingArray;
    },

    /**
     * 获取手牌长度
     * @returns {*|number}
     */
    getHandLength : function () {

        var Card = clone(this._handCards.getCards());
        var handlength = ExObject.sumValue (Card);

        // 获取具体的碰杠牌数
        handlength += (this._pengCards.length * 3);
        handlength += (this._gangCards.length * 3);

        return handlength;
    },

    /**
     * 获取牌型分数
     * @param pattern
     * @returns {*}
     */
    getPatternScore : function (pattern) {

        var room = this.getRoom();

        if (pattern == Const.Pattern.KAWUXING
            && room.getOption("isKaWu")) {
            return 4;
        }

        if (pattern == Const.Pattern.PPH
            && room.getOption("isPengPengHu")) {
            return 4;
        }

        return Const.PatternScore[pattern];
    },

    /**
     * 获取最大胡牌型
     * @param patternArray
     * @returns {*}
     */
    getMaxHuPattern: function (patternArray) {

        var maxPattern = null;

        for (var index = 0; index < patternArray.length; ++index) {

            if (!maxPattern) {
                maxPattern = patternArray[index];
            }else {

                var maxScores = this.getPatternScore (maxPattern);
                var tempScores = this.getPatternScore (patternArray[index]);

                if (maxScores < tempScores) {
                    maxPattern = patternArray[index];
                    maxScores = tempScores;
                }
            }
        }

        return maxPattern;
    },

    /**
     * 检查是否有和碰相同的牌
     * @param card
     */
    checkSamePeng : function (card) {

        for (var index = 0; index < this._pengCards.length; ++index) {

            if (this._pengCards[index] == card) {
                return true;
            }
        }

        return false;
    },

    /**
     * 结算时调用 用于获取玩家的牌型根据清一色发生的变化
     * @param pattern
     * @returns {*}
     */
    checkQingYiSe: function (pattern) {

        // 获取当前玩家所有的碰牌以及杠牌和手牌的花色
        var handCards = clone(this._handCards.getCards());
        var colors = this.getColorsWithCards(handCards); // 表示当前手牌中的花色列表

        var result = clone(pattern);

        // 表示当前是清一色
        // 需要更换当前的胡的牌型
        if (colors.length == 1) {

            switch (result) {
                case Const.Pattern.NORMAL:result = Const.Pattern.QINGYISE;break;
                case Const.Pattern.PAIR7:result = Const.Pattern.QINGPAIR7;break;
                case Const.Pattern.KAWUXING:result = Const.Pattern.QINGKAWUXING;break;
                case Const.Pattern.HHPAIR7:result = Const.Pattern.QINGHHPAIR7;break;
                case Const.Pattern.MINGSIGUI:result = Const.Pattern.QINGMINGSIGUI;break;
                case Const.Pattern.ANSIGUI:result = Const.Pattern.QINGANSIGUI;break;
                case Const.Pattern.SHOUZHUAYI:result = Const.Pattern.QINGSHOUZHUAYI;break;
                case Const.Pattern.PPH:result = Const.Pattern.QINGPPH;break;
            }
        }

        return result;
    },

     checkDaSanYuan : function (bb, hz, fc) {

        if (bb >= 3 && fc >= 3 && hz >= 3) {
            return true;
        }

        return false;
    },

    checkXiaoSanYuan : function (bb, hz, fc) {

        if (bb == 2 && hz >= 3 && fc >= 3) {
            return true;
        }

        if (hz == 2 && bb >= 3 && fc >= 3) {
            return true;
        }

        if (fc == 2 && hz >= 3 && bb >= 3) {
            return true;
        }

        return false;
    },

    checkSanYuan : function (pattern, tingCards) {

        // 获取中重复的数量
        var hzRelax = 0;

        // 获取发重复的数量
        var fcRelax = 0;

        // 获取白重复的数量
        var bbRelax = 0;

        // 获取碰牌
        for (var index = 0; index < this._pengCards.length; ++index) {

            if (this._pengCards[index] == MJ.ZI.BB) {
                bbRelax += 3;
            }

            if (this._pengCards[index] == MJ.ZI.HZ) {
                hzRelax += 3;
            }

            if (this._pengCards[index] == MJ.ZI.FC) {
                fcRelax += 3;
            }
        }

        // 获取杠牌
        for (var index = 0; index < this._gangCards.length; ++index) {

            if (this._gangCards[index].card == MJ.ZI.BB) {
                bbRelax += 4;
            }

            if (this._gangCards[index].card == MJ.ZI.HZ) {
                hzRelax += 4;
            }

            if (this._gangCards[index].card == MJ.ZI.FC) {
                fcRelax += 4;
            }
        }

        // 获取手牌
        var handCards = clone(this._handCards.getCards());

        var length = this.getHandLength();
        if (length == 13) {
            ExObject.addNumber(handCards, tingCards, 1);
        }

        for (var index in handCards) {

            if (index) {

                if (index == MJ.ZI.BB) {
                    bbRelax += handCards[index];
                }

                if (index == MJ.ZI.HZ) {
                    hzRelax += handCards[index];
                }

                if (index == MJ.ZI.FC) {
                    fcRelax += handCards[index];
                }
            }
        }

        // 判断小三元
        if (this.checkXiaoSanYuan(bbRelax, hzRelax, fcRelax)) {
            return Const.Pattern.XIAOSANYUAN;
        }

        // 判断大三元
        if (this.checkDaSanYuan(bbRelax, hzRelax, fcRelax)) {
            return Const.Pattern.DASANYUAN;
        }

        return pattern;
    },

    checkKaWuXin : function (pattern, Card) {

        if (pattern != Const.Pattern.NORMAL) {
            return pattern;
        }

        // 字牌和牌值不是5的不需要判断卡五星
        if (MJ.getColor (Card) == MJ.Color.ZI || MJ.getPoint (Card) != 5) {
            return pattern;
        }

        // 获取手牌数
        var handCards = clone(this._handCards.getCards());

        var length = this.getHandLength();
        if (length == 13) {
            ExObject.addNumber(handCards, Card, 1);
        }

        var huColor = MJ.getColor(Card);
        var huColorCards = MJ.getColorCards(handCards, huColor);
        var huColorMinCard = MJ.getValue(huColor, 1);
        var huColorMaxCard = MJ.getValue(huColor, MJ.COLOR_CARD_NUM);

        var colorSplits = MJ.splitColorCards(huColorMinCard, huColorMaxCard, huColorCards);
        var isJiaXinWu = false;
        colorSplits.forEach(function(items) {
            items.forEach(function (item) {
                if (item.length == 3) {

                    if (item[0] != item[1]) { //不是三张一样的牌
                        if (Card == item[1]) { //夹张
                            isJiaXinWu = true;
                        }
                    }
                }
            });
        }.bind(this));

        if (isJiaXinWu) {
            return Const.Pattern.KAWUXING;
        }

        return pattern;
    },

    checkAnSiGui : function (pattern, tingCards) {

        var handCards = clone (this._handCards.getCards());
        var length = this.getHandLength();
        if (length == 13) {
            ExObject.addNumber(handCards, tingCards, 1);
        }

        // 判断暗四归
        if (handCards[tingCards] == 4) {
            return Const.Pattern.ANSIGUI;
        }

        return pattern;
    },

    checkMingSiGui : function (pattern, tingCard) {

        var handCards = clone (this._handCards.getCards());
        var length = this.getHandLength();
        if (length == 13) {
            ExObject.addNumber(handCards, tingCard, 1);
        }

        // 获取玩家的碰牌列表
        if (this.checkSamePeng (tingCard)){
            return Const.Pattern.MINGSIGUI;
        }

        return pattern;
    },

    checkHuPatternWithCard : function (card, pattern) {

        var patternArray = [];

        patternArray.push (pattern);

        pattern = this.checkKaWuXin(pattern, card);
        if (pattern == Const.Pattern.KAWUXING) {
            pattern = this.checkQingYiSe(pattern);
            patternArray.push (pattern);
        }

        pattern = this.checkMingSiGui(pattern, card);
        if (pattern == Const.Pattern.MINGSIGUI) {
            pattern = this.checkQingYiSe(pattern);
            patternArray.push (pattern);
        }

        pattern = this.checkAnSiGui(pattern, card);
        if (pattern == Const.Pattern.ANSIGUI) {
            pattern = this.checkQingYiSe(pattern);
            patternArray.push (pattern);
        }

        pattern = this.checkSanYuan(pattern, card);
        if (pattern == Const.Pattern.XIAOSANYUAN
            || pattern == Const.Pattern.DASANYUAN) {
            patternArray.push (pattern);
        }

        if (patternArray.length >= 1) {
            // 选出最大牌型
            pattern = this.getMaxHuPattern (patternArray);
        }

        pattern = this.checkQingYiSe(pattern);

        return pattern;

    },

    /**
     * 算牌型逻辑
     */
    checkSettlementPattern : function () {

        // 获取胡牌内容
        var tingCards = clone(this.getTingCards());
        var finalArray = [];

        for (var index = 0; index < tingCards.length; ++index) {

            var pattern = tingCards[index].pattern;
            var card = tingCards[index].card;

            if (pattern && pattern != Const.Pattern.NONE) {

                pattern = this.checkHuPatternWithCard (card, pattern);

                finalArray.push (pattern);
            }
        }

        var newPattern = Const.Pattern.NONE;

        var scores = Const.PatternScore[newPattern];

        if (finalArray.length >= 1) {
            // 选出最大牌型
            newPattern = this.getMaxHuPattern (finalArray);
            scores = this.getPatternScore (newPattern);
        }

        this.setRoundPattern(newPattern, scores);
    },

    settlementGangScore : function () {
        this.addRoundGangScore(this._gangScore);
        this.addRoundScore(this._gangScore);
    },

    cancelLastGangForQG: function(card) {
        var gangInfo = this._super(card);

        if (gangInfo) {
            var gangNum = this.getRoom().getCurGang();
            if (gangNum > 0 && this._gangCards.length > 0) {
                this._gangCards[this._gangCards.length - 1].unscored = 1;
            }
        }

        return gangInfo;
    },

    /******************************************************************
     * 重载的接口
     ******************************************************************/

    getInfo: function() {
        var info = this._super();
        return info;
    },

    getReconnectInfo: function(isSelf) {
        var info = this._super(isSelf);
        info.piao = this._selectPiao;

        if (this.isBaoTing()) {
            info.LDResult = this._LDResult;
            info.tingCard = this.getTingCards();
        }

        return info;
    },

    getSettlementInfo: function() {
        var info = this._super();

        info.huCount = this._huCount;
        info.dealerCount = this._dealerCount;
        info.dianCount = this._dianCount;

        info.handCards = this._handCards.getCards();
        info.pengCards = this._pengCards;
        info.gangCards = this._gangCards;

        info.isBaoTing = this.isBaoTing();

        if (this._selectPiao != -1) {
            info.piao = this._selectPiao;
        }

        if (this.getRoom().getOption("isNumKan")) {
            info.kan = this._kanNum;
        }

        if (this.getRoom().getOption("isBuyMa") != 0) {
            info.maScore = this._maScore;
        }

        return info;
    },

    onCurRoundFinished: function () {
        this._super();

        this._maScore = 0;
        this._huCardType = {};
        this._kanNum = 0;
        this._gangScore = 0;
        this._isZM = false;
        this._showStatus = false;
        this._LDResult = {};
    },

    //getInitHandCardPreCards: function() {
    //    var preCards = [];
    //
    //    var distance = this.getRoom().getIndexDistance(this.getRoom().getDealerIndex(), this.getIndex());
    //    if (distance == 0) {
    //
    //    } else if (distance == 1) {
    //        preCards.push(MJ.ZI.HZ);
    //        preCards.push(MJ.ZI.FC);
    //        preCards.push(MJ.ZI.BB);
    //
    //        preCards.push(MJ.getValue(MJ.Color.TONG, 5));
    //        preCards.push(MJ.getValue(MJ.Color.TONG, 7));
    //        preCards.push(MJ.getValue(MJ.Color.TONG, 8));
    //        preCards.push(MJ.getValue(MJ.Color.TONG, 9));
    //
    //        preCards.push(MJ.getValue(MJ.Color.TIAO, 6));
    //        preCards.push(MJ. getValue(MJ.Color.TIAO, 7));
    //        preCards.push(MJ.getValue(MJ.Color.TIAO, 8));
    //
    //        preCards.push(MJ.getValue(MJ.Color.WAN, 2));
    //        preCards.push(MJ.getValue(MJ.Color.WAN, 2));
    //        preCards.push(MJ.getValue(MJ.Color.WAN, 2));
    //    }
    //
    //    return preCards;
    //},

    /******************************************************************
     * 需要重载的接口
     ******************************************************************/

    /**
     * 检查胡牌的逻辑
     * @param cards
     */
    checkHuLogic: function(cards, huCard) {
        var num4 = 0;
        var num3 = 0;
        var num2 = 0;
        var num = 0;

        ExObject.each(cards, function(c, n) {
            if (n == 2) {
                num2++;
            } else if (n == 3) {
                num3++;
            } else if (n == 4) {
                num4++;
            }
            num += n;
        });

        if (num == 2) { // 单调
            return (num2 == 1) ? Const.Pattern.SHOUZHUAYI : Const.Pattern.NONE;
        }

        // 特殊情况
        var Card = clone(this._handCards.getCards());
        var handlength = ExObject.sumValue (Card);

        if (handlength == 1) {
            return Const.Pattern.SHOUZHUAYI;
        }

        if ((num2 + num4*2) == 7) { // 七对

            if (num4 >= 1) { // 豪华七对
                return Const.Pattern.HHPAIR7;
            }

            return Const.Pattern.PAIR7;
        }

        if (num2 == 1 && (num3 * 3 + 2) == num) { // 碰碰胡
            return Const.Pattern.PPH;
        }

        var room = this.getRoom();
        var colors = room.getSubConfig().colors;

        var pattern = MJ.Pattern.NORMAL;
        for (var i = 0, l = colors.length; i < l; ++i) {
            var color = colors[i];
            var colorCards = MJ.getColorCards(cards, color);

            if (MJ.isBasicColor(color)) {
                if (!MJ.checkHuColorCards(MJ.getValue(color, 1), MJ.getValue(color, MJ.COLOR_CARD_NUM), colorCards)) {
                    pattern = MJ.Pattern.NONE; break;
                }
            } else {
                if (!MJ.checkPairHuColorCards(colorCards)) {
                    pattern = MJ.Pattern.NONE; break;
                }
            }
        }

        return pattern;
    }

});